using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SmartLink.Domain.Entity;
using SmartLink.Domain.IServices;
using SmartLink.Infrastructure;
using SmartLink.IRepository;
using SmartLink.EnumLibrary;
using SmartLink.Domain.ExpandEntity.Base;
using SmartLink.DTOS;
using SmartLink.Infrastructure.Cache;
using SmartLink.Domain.ExpandEntity;

namespace SmartLink.Domain.Services
{
    public class SYS_UserServices : ISYS_UserServices
    {
        private ISYS_UserRepo _userRepository;
        private IBIZ_UserToOrganizationRepo _iBIZ_UserToOrganizationRepo;
        private IPER_UserToRoleRepo _IPER_UserToRoleRepo;
        private IBIZ_OrganizationRepo _IBIZ_OrganizationRepo;

        public SYS_UserServices(ISYS_UserRepo userRepository,
                               IBIZ_UserToOrganizationRepo iBIZ_UserToOrganizationRepo,
                               IPER_UserToRoleRepo iPER_UserToRoleRepo,
                               IBIZ_OrganizationRepo iBIZ_OrganizationRepo)
        {
            _userRepository = userRepository;
            _iBIZ_UserToOrganizationRepo = iBIZ_UserToOrganizationRepo;
            _IPER_UserToRoleRepo = iPER_UserToRoleRepo;
            _IBIZ_OrganizationRepo = iBIZ_OrganizationRepo;
        }

        #region checked

        public OperationResult CheckLogin(string account, string password)
        {
            var user = _userRepository.GetUserByAccount(account);
            if (user == null || user.IsDel)
                return new OperationResult(OperationResultType.QueryNull, "该用户名错误或不存在，请重新输入。");
            if (user.UserStatus == UserStatusEnum.禁用)
                return new OperationResult(OperationResultType.Warning, "账户已禁用，请联系管理员。");
            var pwdEncrypt = SecurityHelper.ToMd5(password.ToUpper() + user.CreateTime.ToString("yyyyMMdd"));
            if (!pwdEncrypt.Contains(user.PassWord))
            {
                return new OperationResult(OperationResultType.Warning, "密码不正确，请重新输入。");
            }

            //所属企业状态检查
            var orgStatus = _iBIZ_UserToOrganizationRepo.GetUserOrginzationStatus(user.ID);
            if (orgStatus != OrgStatusEnum.启用)
                return new OperationResult(OperationResultType.Warning, "您所在的企业未启用。");

            //所属角色状态检查
            var role = _IPER_UserToRoleRepo.GetUserRoles(user.ID).FirstOrDefault();
            if (role != null && role.Enabled == 0)
                return new OperationResult(OperationResultType.Warning, "您所在的角色组未启用。");

            return new OperationResult(OperationResultType.Success, "登陆成功。", user);
        }

        public CurrentUserInfo GetCurrentUserInfo(int userId)
        {
            CurrentUserInfo currentUserInfo = new CurrentUserInfo();
            dynamic userInfo = _userRepository.GetUserCertificate(userId);
            currentUserInfo.UserId = userId;
            currentUserInfo.AccountName = userInfo.AccountName==null?"":userInfo.AccountName.ToString();
            currentUserInfo.NickName = userInfo.NickName == null ? "" : userInfo.NickName.ToString();
            currentUserInfo.UserEmail = userInfo.UserEmail == null ? "" : userInfo.UserEmail.ToString();
            currentUserInfo.UserMobile = userInfo.UserMobile == null ? "" : userInfo.UserMobile.ToString();
            currentUserInfo.OID = Convert.ToInt32(userInfo.OID==null?-1: userInfo.OID);
           // currentUserInfo.ODID = Convert.ToInt32(userInfo.OD_ID == null ? -1 : userInfo.OD_ID);
            currentUserInfo.RoleId = userInfo.RID == null ? -1 : Convert.ToInt32(userInfo.RID);
            currentUserInfo.OrganizationName = userInfo.OrganizationName == null ? "" : userInfo.OrganizationName.ToString();
           // currentUserInfo.DepartmentName = userInfo.DepartmentName == null ? "" : userInfo.DepartmentName.ToString();
            currentUserInfo.RoleName = userInfo.RoleName == null ? "" : userInfo.RoleName.ToString();
            currentUserInfo.HasUpdatedPwdSelf = Convert.ToBoolean(userInfo.HasUpdatedPwdSelf);
            currentUserInfo.UserType = userInfo.UserType == null ? UserTypeEnum.平台用户: Convert.ToInt32(userInfo.UserType);
            
            if (currentUserInfo.UserType ==(int)UserTypeEnum.平台用户)
            {
                currentUserInfo.OpenID = userInfo.OpenID == null ? "" : Convert.ToInt32(userInfo.OpenID);
                currentUserInfo.ROID = _IBIZ_OrganizationRepo.GetRootOrganizationId(currentUserInfo.OID);
                currentUserInfo.RootOrgDescendantsIds = _IBIZ_OrganizationRepo.GetRootOrgDescendantsIds(currentUserInfo.ROID);
            }
            return currentUserInfo;
        }

        public bool Update(SYS_User user)
        {
            return _userRepository.Update(user);
        }

        public void Update(SYS_User user, int oid, int? newDeptId)
        {
            if (!newDeptId.HasValue)
            {
                Update(user);
                return;
            }

            var tran = _userRepository.TranCreate();
            _userRepository.Update(user, tran);
            _iBIZ_UserToOrganizationRepo.DeleteByUserId(user.ID, tran);
            var uto = new BIZ_UserToOrganization
            {
                UserID = user.ID,
                OID = oid,
                OD_ID = newDeptId
            };
            _iBIZ_UserToOrganizationRepo.Add(uto, tran);
            tran.Commit();
        }

        #endregion


        public bool ExistAcountName(string accountName)
        {
            return _userRepository.ExistAccountName(accountName);
        }

        public bool ExistUserEmail(string userEmail)
        {
            return _userRepository.ExistUserEmail(userEmail);
        }

        public int GetUserIDByAccountName(string accountName)
        {
            return _userRepository.GetUserIdByName(accountName);
        }

        public SYS_User GetById(int id)
        {
            return _userRepository.GetById(id);
        }

        #region 用户管理

        public bool Add(SYS_User user, BIZ_UserToOrganization userToOrg)
        {
            DbTransaction dbtransaction = _userRepository.TranCreate();
            dynamic userId = _userRepository.Add(user, dbtransaction);
            userToOrg.UserID = userId;
            dynamic id = _iBIZ_UserToOrganizationRepo.Add(userToOrg, dbtransaction);
            dbtransaction.Commit();
            return true;
        }

        public bool UpdateUserInfo(SYS_User user, BIZ_UserToOrganization userToOrg, PER_UserToRole userToRole)
        {
            DbTransaction dbtransaction = _userRepository.TranCreate();
            try
            {
                //删除关系
                _iBIZ_UserToOrganizationRepo.DeleteByUserId(userToOrg.UserID, dbtransaction);
                _IPER_UserToRoleRepo.DeleteByUserId(userToOrg.UserID, dbtransaction);

                _userRepository.Update(user, dbtransaction);
                _iBIZ_UserToOrganizationRepo.Add(userToOrg, dbtransaction);
                _IPER_UserToRoleRepo.Add(userToRole, dbtransaction);

                dbtransaction.Commit();
            }
            catch (Exception ex)
            {
                dbtransaction.Rollback();
                return false;
            }
            return true;
        }



        public void Delete(int userId)
        {
            _userRepository.Delete(userId);
        }



        public IList<dynamic> GetUserList(string odidStr)
        {
            return _userRepository.GetUserList(odidStr);
        }

        public IEnumerable<dynamic> GetPaged(int? oid, int? odid, UserStatusEnum? userStatus, string keyWord, int curUserId, Pagination pagination)
        {
            return _userRepository.GetPaged(oid, odid, userStatus, keyWord, curUserId, pagination, CurrentUser.IsSuperAdmin, CurrentUser.IsOrgAdmin);
        }

        public dynamic GetUserInfo(int id)
        {
            return _userRepository.GetUserInfo(id);
        }

        #endregion

        public static string EncryptPassword(string originPassword, DateTime userCraeteTime)
        {
            return SecurityHelper.ToMd5(originPassword.ToUpper() + userCraeteTime.ToString("yyyyMMdd"));
        }

        public OperationResult UpdatePassword(int userId, string password, bool kickOut = false, PlatformEnum? platform = null)
        {
            var userEntity = _userRepository.GetById(userId);
            userEntity.PassWord = EncryptPassword(password, userEntity.CreateTime);
            userEntity.HasUpdatedPwdSelf = true;
            var success = _userRepository.Update(userEntity);
            if (success)
            {
                if (kickOut)
                    UserInfoCaches.TokenDelete(userId, platform);
                return new OperationResult(OperationResultType.Success);
            }
            else
                return new OperationResult(OperationResultType.Error);
        }

        public OperationResult ForceUpdatePassword(string password)
        {
            var userCache = UserInfoCaches.GetUserInfoCache(CurrentUser.Current.UserId);
            UserInfoCaches.UpdateLoginCacheForHasUpdatedPwdSelf(userCache);

            return UpdatePassword(CurrentUser.Current.UserId, password);
        }

        public OperationResult ResetPassword(int userId)
        {
            return UpdatePassword(userId, ConstData.DefaultUserPassword, true);
        }

        public IEnumerable<UserSelectItemExpand> GetUserSelectList(int orgId, bool isDept)
        {
            return _userRepository.GetUserSelectList(orgId, isDept);
        }

        
    }
}
